import React, {Component} from "react";
import {
  Table,
  Badge,
  Card,
  Input,
  Select,
  message,
  Modal,
} from 'antd';
import {connect} from "dva";
import SearchForm from '../../components/AutoForm/SearchForm';
import EditForm from '../../components/AutoForm/EditForm';
const {Option} = Select;
const TextArea = Input.TextArea;
const confirm = Modal.confirm;
const statusMap = ['processing', 'warning'];
const status = ['使用中', '锁定'];

const columns = [
  {
    title: '编码',
    width: "280px",
    dataIndex: 'code',
  },
  {
    title: '名称',
    width: "240px",
    dataIndex: 'name',
  },
  {
    title: 'Action',
    width: "205px",
    dataIndex: 'action',
  },
  {
    title: '图标',
    width: "160px",
    dataIndex: 'icon',
  },
  {
    title: '描述',
    width: "360px",
    dataIndex: 'descr'
  },
  {
    title: '锁定/使用',
    width: "120px",
    dataIndex: 'isLock',
    render(val) {
      return <Badge status={statusMap[val]} text={status[val]}/>;
    },
  },
];

const fields = [
  {
    cols: [
      {
        md: 6,
        label: '名称',
        name: 'name',
        component: <Input placeholder="请输入"/>
      },
      {
        md: 6,
        label: '编码',
        name: 'code',
        component: <Input placeholder="请输入"/>
      },
      {
        md: 6,
        label: '使用状态',
        name: 'isLock',
        component: <Select placeholder="请选择" style={{width: '100%'}}>
          <Option value="0">使用中</Option>
          <Option value="1">锁定</Option>
        </Select>
      }
    ]
  }
]

@connect(({btnGroup, btnGroupType, loading}) => ({
  tableLoading: loading.effects['btnGroup/page'],
  modalInsertLoading: loading.effects['btnGroup/insert'],
  modalUpdateLoading: loading.effects['btnGroup/update'],
  searchForm: btnGroup.searchForm,
  modalForm: btnGroup.modalForm,
  addForm: btnGroup.addForm,
  modalVisible: btnGroup.modalVisible,
  tableData: btnGroup.list,
  selection: btnGroup.selection,
  pagination: btnGroup.pagination,
  optFlag: btnGroup.optFlag,

}))
export default class List extends Component {

  componentDidMount() {
    const {dispatch, pagination} = this.props;
    dispatch({
      type: 'btnGroup/page',
      payload: pagination
    })
  }

  handleSearch = (page) => {
    const {dispatch, pagination, searchForm} = this.props;
    let pageParam = {pageSize: pagination.pageSize, current: pagination.current}
    if (page) {
      pageParam = {pageSize: page.pageSize, current: page.current}
    }
    let searchValue = {};
    Object.keys(searchForm).map((key) => {
      searchValue[key] = searchForm[key]['value'];
    })
    const param = {
      ...searchValue,
      ...pageParam
    };
    dispatch({
      type: 'btnGroup/page',
      payload: param
    })
  }

  handleSearchChange = (fields) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'btnGroup/handleSearchChange',
      payload: fields
    })
  }

  handleModalVisible = (opt) => {
    const {dispatch, modalVisible, selection, addForm} = this.props;
    let payload = {modalVisible: !modalVisible};
    let modalForm = {
      type: {value: 'BTN-GROUP'}
    };
    if ('edit' === opt) {
      if (JSON.stringify(selection) === '{}') {
        message.error('请选择一条记录');
        return;
      } else {
        Object.keys(selection).map((key) => {
          modalForm[key] = {value: selection[key]}
        })
      }
    } else if ("add" === opt) {
      Object.keys(addForm).map((key) => {
        modalForm[key] = {value: addForm[key]}
      })
    }

    if (!modalVisible) {
      payload.optFlag = opt;
      payload.modalForm = modalForm;
    }
    dispatch({
      type: 'btnGroup/handleModalVisible',
      payload: payload
    })
  }

  handleModalChange = (fields) => {
    const {dispatch, optFlag, addForm} = this.props;
    const payload = {fields: fields, optFlag: optFlag, addForm: addForm};
    dispatch({
      type: 'btnGroup/handleModalChange',
      payload: payload
    })
  }

  handleTableChange = (pagination) => {
    this.handleSearch(pagination);
  }

  handleOk = (fields) => {

    const {dispatch, optFlag, searchForm, pagination} = this.props;
    const payload = {
      fields: fields,
      searchForm: searchForm,
      pagination: pagination
    }
    if (optFlag === 'add') {
      dispatch({
        type: 'btnGroup/insert',
        payload: payload
      })
    } else if (optFlag === 'edit') {
      dispatch({
        type: 'btnGroup/update',
        payload: payload
      })
    }

  }

  onSelect = (record)=> {
    const {dispatch} = this.props;

    dispatch({
      type: 'btnGroup/handleTableSelection',
      payload: record
    })
  };

  handleDel = (key) => {
    debugger
    const {dispatch, selection, searchForm, pagination } = this.props;
    if (JSON.stringify(selection) === '{}') {
      message.error('请选择一条记录');
      return;
    }
    const payload = {
      fields: selection,
      searchForm: searchForm,
      pagination: pagination
    }
    confirm({
      title: '是否确认删除行内操作?',
      content: `编码：${selection.code}; 名称：${selection.name}`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'btnGroup/del',
          payload: payload,
        });
      },
      onCancel() {
      },
    });
  }
  render() {
    const {
      pagination,
      tableLoading,
      modalInsertLoading,
      modalUpdateLoading,
      tableData,
      modalVisible,
      modalForm,
      searchForm,
      optFlag
    } = this.props;
    const EditRows = [
      {
        cols: [
          {
            label: '名称',
            name: 'name',
            md: 18,
            rules: [{required: true, message: '请输入名称！'}],
            component: <Input placeholder="请输入名称"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '编码',
            name: 'code',
            md: 18,
            rules: [{required: true, message: '请输入至少四个字符！', min: 4}],
            component: <Input placeholder="请输入编码"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '类型',
            name: 'type',
            md: 18,
            rules: [{required: true, message: '请选择类型'}],
            component: <Input disabled={true} placeholder="请确认类型"/>
          }
        ]
      },
      {
        cols: [
          {
            label: 'Action',
            name: 'action',
            md: 18,
            rules: [{required: true, message: '请输入Action'}],
            component: <Input placeholder="请输入Action"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '图标',
            name: 'icon',
            md: 18,
            component: <Input placeholder="请输入图标"/>
          },
        ]
      },
      {
        cols: [
          {
            label: '描述',
            name: 'descr',
            md: 18,
            component: <TextArea placeholder="请输入描述"/>
          },
          {
            name: 'id',
            component: <Input type="hidden"/>
          }
        ]
      }
    ];

    const showTotal = (total) => {
      return `总记录： ${total} 条`;
    }
    pagination.showTotal = showTotal;
    const rowSelection = {
      type: "radio",
      onSelect: this.onSelect
    };

    return (
      <Card bodyStyle={{padding: 0}}>
        <SearchForm
          header="表格行内元素->操作"
          layout="inline"
          fields={fields}
          fieldValue={searchForm}
          onSubmit={this.handleSearch}
          onModal={this.handleModalVisible}
          onFieldsChange={this.handleSearchChange}
          onDel={this.handleDel}
        />
        <Table
          pagination={pagination}
          columns={columns}
          loading={tableLoading}
          dataSource={tableData}
          rowSelection={rowSelection}
          rowKey={record => record.id}
          scroll={{x: 'max-content'}}
          size="small"
          onChange={this.handleTableChange}
          bordered
        />

        <EditForm
          rows={EditRows}
          fieldValue={modalForm}
          onFieldsChange={this.handleModalChange}
          optFlag={optFlag}
          visible={modalVisible}
          onOk={this.handleOk}
          onCancel={this.handleModalVisible}
          confirmLoading={modalInsertLoading || modalUpdateLoading}
        />
      </Card>
    )
  }
}
